<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/9/28
 * Time: 13:46
 */
namespace App\Service\Admin;

use App\Http\Model\MongoDB\ShopTemplate;
use App\Utils\UploadAliOss;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
use App\Utils\WechatUtil;
use App\Http\Model\Mysql\UploadLogModel;

class DecorationService extends BaseService
{
    /**
     * 页面列表
     * @param int $type 页面类型
     * @param int $page 当前页面
     * @param int $size 每页数量
     * @return array
     */
    public function templateBasic(int $type = 0, int $page = 1, int $size = self::PAGE_LIMIT)
    {
        $where['templateType']  =   $type == ShopTemplate::SPECIAL_TEMPLATE ? ShopTemplate::SPECIAL_TEMPLATE : ShopTemplate::BASIC_TEMPLATE;
        $where['companyId']     =   '621b9cc5-11b3-4d0e-ad82-981351e25336';
        $where['appId']         =   '530defda-cb12-4d24-b0e8-dbfabb76393b';

        $size   =   $size <= 0 ? self::PAGE_LIMIT : $size;
        $count  =   ShopTemplate::where($where)->count();
        $list   =   ShopTemplate::where($where)->limit($size)->offset(($page - 1) * $size)->orderBy('sortOrder', 'desc')->select(['_id', 'templateName', 'page', 'pageTitle', 'sortOrder'])
                    ->get()->each(function (&$item) {
                        $item->pageTitle = $item->pageTitle ?? '';
                    });

        if ($list->isEmpty()) {
            return [true, []];
        } else {
            return [true, [
                'count' =>  $count,
                'pages' =>  ceil($count / $size),
                'current'=> $page,
                'list'  =>  $list->toArray()
            ]];
        }
    }

    /**
     * 专题页面列表
     * @param array $query  搜索条件
     * @param int $page     当前页面
     * @return array
     */
    public function templateSpecial(array $query = [], int $page = 1)
    {
        $where['templateType']  =   ShopTemplate::SPECIAL_TEMPLATE;
        $where['companyId']     =   '621b9cc5-11b3-4d0e-ad82-981351e25336';
        $where['appId']         =   '530defda-cb12-4d24-b0e8-dbfabb76393b';
        if (isset($query['template_name']) && !empty($query['template_name'])) {
            $where['templateName']  =   $query['template_name'];
        }

        $count  =   ShopTemplate::where($where)->count();
        $list   =   ShopTemplate::where($where)->limit(self::PAGE_LIMIT)->offset(($page - 1) * self::PAGE_LIMIT)->orderBy('sortOrder', 'desc')->select(['_id', 'templateName', 'page', 'pageTitle', 'sortOrder'])->get();

        if ($list->isEmpty()) {
            return [true, []];
        } else {
            return [true, [
                'count' =>  $count,
                'pages' =>  ceil($count / self::PAGE_LIMIT),
                'current'=> $page,
                'list'  =>  $list->toArray()
            ]];
        }
    }

    /**
     * 模板标题修改
     * @param string $template_id  模板ID
     * @param string $template_name 模板页面标题
     * @return array
     */
    public function templateTitle(string $template_id, string $template_name)
    {
        $update_result  =   ShopTemplate::where(['_id' => $template_id])->update(['pageTitle' => $template_name]);
        if ($update_result) {
            return [true, '修改成功'];
        } else {
            return [false, '修改失败'];
        }
    }

    /**
     * 模板内容详情
     * @param string $template_id  模板ID
     * @return array
     */
    public function templateInfo(string $template_id)
    {
        $info_result    =   ShopTemplate::where(['_id' => $template_id])->select(['_id', 'preview', 'templateName', 'templateType', 'page', 'pageTitle', 'companyId', 'appId', 'sortOrder'])->first();
        if (empty($info_result)) {
            return [false, '模板不存在'];
        } else {
            return [true, $info_result];
        }
    }

    /**
     * 模板图片上传
     * @param UploadedFile $file 上传的图片文件
     * @return array
     */
    public function templateUpload(UploadedFile $file)
    {
        $setting_path   =   Config::get('upload.local_path');
        $upload_path    =   public_path($setting_path);
        $extension      =   $file->extension();
        $name           =   $file->getFilename();
        $file_name      =   sha1($file->getClientOriginalName() . createRandomNumber()) . '.' . $extension;
        $file_type      =   $file->getType();
        $file_size      =   $file->getSize();
        try {
            $file->move($upload_path, $file_name);
            $move_name      =   $upload_path . DIRECTORY_SEPARATOR . $file_name;
            $upload_util    =   new UploadAliOss();
            [$flag, $result]=   $upload_util->uploadFile([$file_name => $move_name]);
            $flag ? @unlink($move_name) : NULL;
            $move_name      =   $flag ? $result[$file_name] : URL::asset($setting_path . '/' . $file_name);
            $file_unique    =   createUniqueID();

            if (!$flag) {
                return [false, $result];
            }
            UploadLogModel::create([
                'file_url'  =>  $move_name,
                'extension' =>  $extension,
                'file_type' =>  $file_type,
                'file_unique'=>  $file_unique,
                'file_size' =>  $file_size,
                'upload_user'=> request()->input('admin_user')['user_id'] ?? 0
            ]);
            return [true, [
                'url'       =>  $move_name,
                'extension' =>  $extension,
                'file_unique'=> $file_unique
            ]];
        } catch (\Exception $e) {
            return [false, $e->getMessage()];
        }
    }

    /**
     * 模板预览设置
     * @param array $preview_setting 预览设置
     * @param string $template_id   模板ID
     * @return array
     */
    public function templatePreview(array $preview_setting, string $template_id)
    {
        if (empty($preview_setting)) {
            return [false, '设置不能为空'];
        }

        $update_result  =   ShopTemplate::where(['_id' => $template_id])->update(['preview' => $preview_setting]);
        if ($update_result) {
            return [true, '设置成功'];
        } else {
            return [false, '设置失败'];
        }
    }

    /**
     * 模板发布设置
     * @param string $template_id   模板ID
     * @return array
     */
    public function templateRelease(string $template_id)
    {
        $release_setting=   ShopTemplate::where(['_id' => $template_id])->select(['_id', 'preview'])->first();
        if (empty($release_setting) || empty($release_setting->preview)) {
            return [false, '设置不能为空'];
        }
        $update_result  =   ShopTemplate::where(['_id' => $template_id])->update(['release' => $release_setting->preview]);
        if ($update_result) {
            return [true, '发布成功'];
        } else {
            return [false, '发布失败'];
        }
    }

    /**
     * 装修店铺预览二维码生成
     * @param string $template_id
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function templateCode(string $template_id)
    {
        $release_setting=   ShopTemplate::where(['_id' => $template_id])->select(['_id', 'page'])->first();
        if (empty($release_setting) || empty($release_setting->page)) {
            return [false, '二维码地址不存在'];
        }

        $admin_info     =   request()->post('admin_user');
        [$flag, $result]    =   WechatUtil::getUnlimitedCode(['scene' => 'decoration'], $admin_info['user_id']);        //, 'page' => $release_setting->page . '?template_id=' . $template_id
        if ($flag && isset($result['img_path'])) {
            return [true, file_get_contents($result['img_path'])];
        } else {
            return [false, '二维码地址获取失败'];
        }
    }

}
